package cd.zhixuan.utils;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.ref.WeakReference;

import cd.zhixuan.utils.dialog.Toaster;

/**
 * @author CHAO
 * Create Time: 2021.12.30 14:51
 **/
public final class GlobalTools {
    public static final boolean DEBUG = true;

    private static Context mContext;
    private static Handler mainHandler;

    /**
     * 在Application初始化时调用
     *
     * @param context application
     */
    public static void init(Context context) {
        mContext = context;
        mainHandler = new Handler();
        if (mContext instanceof Application) {
            //注册全局activity状态监听
            ((Application) mContext).registerActivityLifecycleCallbacks(new OnActivityLifecycleCallbacks());
        }
    }

    public static Context getContext() {
        return mContext;
    }

    public static void runOnUiThread(Runnable r) {
        mainHandler.post(r);
    }

    public static void runOnUiThread(Runnable r, long delay) {
        mainHandler.postDelayed(r, delay);
    }

    @Nullable
    private static WeakReference<Activity> CURRENT_ACTIVITY;

    @Nullable
    public static Activity getCurrentActivity() {
        WeakReference<Activity> current = CURRENT_ACTIVITY;
        if (current == null) return null;
        final Activity activity = current.get();
        if (activity == null || activity.isFinishing() || activity.isDestroyed()) return null;
        return activity;
    }

    /**
     * activity状态统一监听
     */
    private static final class OnActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

        @Override
        public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

        }

        @Override
        public void onActivityStarted(@NonNull Activity activity) {
            CURRENT_ACTIVITY = new WeakReference<>(activity);
        }

        @Override
        public void onActivityResumed(@NonNull Activity activity) {

        }

        @Override
        public void onActivityPaused(@NonNull Activity activity) {

        }

        @Override
        public void onActivityStopped(@NonNull Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {
            Toaster.destroyActiveToast();
        }
    }
}
